<?php

class News {
	private $db;
	
	public function __construct() {
		$this->db = Db::getInstance ();
	}
	
	function getNews($limit_start, $limit_count) {
		$stmt = $this->db->prepare("SELECT id,title,text_preview,created FROM news ORDER by created DESC LIMIT ?,?");
		$stmt->bindParam(1,$limit_start,PDO::PARAM_INT);
		$stmt->bindParam(2,$limit_count,PDO::PARAM_INT);
		$stmt->execute();
		return $stmt->fetchAll(PDO::FETCH_ASSOC); 
	}
	
	function getNewsId($id){
		$stmt = $this->db->prepare("SELECT id,title,text,created FROM news WHERE id = ?");
		$stmt->bindParam(1,$id,PDO::PARAM_INT);
		$stmt->execute();
		
		return $stmt->fetch(PDO::FETCH_ASSOC);
	}
	
	function commentAdd($comment,$user_id,$news_id){
		$stmt = $this->db->prepare("INSERT INTO news_comment 
		(comment,user_id,news_id,created)
		VALUES
		(?,?,?,?);
		");
		
		$stmt->bindParam(1,$comment,PDO::PARAM_STR,200);
		$stmt->bindParam(2,$user_id,PDO::PARAM_INT);
		$stmt->bindParam(3,$news_id,PDO::PARAM_INT);
		$stmt->bindParam(4,date('Y:n:d H:i:s'),PDO::PARAM_STR);
		$stmt->execute();
	}
	
	function getComments($news_id) {
		$stmt = $this->db->prepare("SELECT news_comment.id,comment,user_id, news_comment.created, users.login AS user_login 
		FROM news_comment 
		JOIN users ON users.id = news_comment.user_id
		WHERE news_id = ?");
		$stmt->bindParam(1,$news_id,PDO::PARAM_INT);
		$stmt->execute();
		
		return $stmt->fetchAll(PDO::FETCH_ASSOC);
	}
	
	function getCountNews() {
		$stmt = $this->db->query("SELECT * FROM news");
		return $stmt->rowCount();
	}
	
	function searchInContent($query) {
		$stmt = $this->db->prepare("SELECT id,title,created FROM news 
		WHERE 
		text LIKE :like_query OR 
		text_preview LIKE :like_query OR
		title LIKE :like_query
		");
		$query = '%'.$query.'%';
		
		$stmt->bindParam(':like_query',$query,PDO::PARAM_STR);
		$stmt->execute();
		
		return $stmt->fetchAll(PDO::FETCH_ASSOC);
	}
	
	
	function addNews($text_preview, $text, $title) {
		$stmt = $this->db->prepare ( "INSERT INTO news 
		(title, text_preview, text, created)
		VALUES
		(?,?,?,?);
		" );
		
		$stmt->bindParam ( 1, $title, PDO::PARAM_STR);
		$stmt->bindParam ( 2, $text_preview, PDO::PARAM_STR);
		$stmt->bindParam ( 3, $text, PDO::PARAM_STR );
		$stmt->bindParam ( 4, date ( 'Y:n:d H:i:s' ), PDO::PARAM_STR );
		$stmt->execute ();
	}
}

?>